package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dataSource.DBContextHolder;
import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.user.entity.Account;
import com.stlm2.dems.util.CoreLogic;
import com.stlm2.util.Convert;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("shopOrderService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class ShopOrderService extends BaseServiceImpl<ShopOrder> {

	@Resource
	private ShopOrderDao shopOrderDao;

	@Resource
	private PurchaseOrderDao purchaseOrderDao;

	@Resource
	private PurchaseOrderService purchaseOrderService;

	@Resource
	private GoodsOrderDao goodsOrderDao;

	@Resource
	private UserCardsDao userCardsDao;

	@Resource
	private UserDao userDao;

	@Resource
	private DdmGoodsDao ddmGoodsDao;

	@Resource
	private DdmShopDao ddmShopDao;

	@Resource
	private ServiceOrderDao serviceOrderDao;

	@Resource
	private ValueAddedServicesDao valueAddedServicesDao;

	@Resource
	private InventoryDao inventoryDao;

	@Resource
	private InventoryLogDao inventoryLogDao;

	@Resource
	private AccountDao accountDao;

	@Resource
	private FmsFlowDao fmsFlowDao;

	@Resource
	private RefundLogDao refundLogDao;

	@Resource
	private GoodSpecificationDao goodSpecificationDao;

	@Resource
	private CoreLogic coreLogic;

	@Override
	protected BaseDao <ShopOrder> getDao() {
		return shopOrderDao;
	}


	/**
	 * 定时任务 取消未支付订单 （创建状态的订单）
	 */
	public void cancelOrder(){
		Date current = new Date();
		Date cancelTime = Convert.beforeDay(current,1);//一天前
		PurchaseOrder param = new PurchaseOrder();
		param.setOrderState(OrderState.Create);
		param.setCreateTime(cancelTime);

		List<PurchaseOrder> purchaseOrderList = purchaseOrderDao.queryList(-1, -1, param);
		if (purchaseOrderList != null && purchaseOrderList.size() > 0) {
			for (PurchaseOrder purchaseOrder : purchaseOrderList) {
				cancelOrder(purchaseOrder,CancelReason.System);
			}
		}

	}
    //有支付申请限制取消
	public Boolean  cancelOrder(PurchaseOrder purchaseOrder,CancelReason cancelReason){
		if(purchaseOrder == null)
			return false;

		synchronized (purchaseOrder) {
			if (!OrderState.Create.equals(purchaseOrder.getOrderState()))
				return false;
			//待做 检验 该订单是否发起支付申请

			/**
			 *
			 */


			//修改一级订单状态
			purchaseOrder.setOrderState(OrderState.Cancel);
			purchaseOrder.setCancelTime(new Date());
			purchaseOrder.setCancelReason(cancelReason);
			purchaseOrderDao.modify(purchaseOrder);

			//修改二级订单状态
			ShopOrder shopOrderParam=new ShopOrder();
			shopOrderParam.setPurchaseOrderCode(purchaseOrder.getCode());
			List<ShopOrder> shopOrderList = shopOrderDao.queryList(-1, -1, shopOrderParam);
			if(shopOrderList != null && shopOrderList.size() > 0){
				for (ShopOrder shopOrder:shopOrderList){
					if(!OrderState.Create.equals(shopOrder.getOrderState()))
						continue;

					shopOrder.setOrderState(OrderState.Cancel);
					shopOrder.setCancelTime(purchaseOrder.getCancelTime());
					shopOrder.setCancelReason(cancelReason);
					shopOrderDao.modify(shopOrder);

					//修改三级订单状态
					GoodsOrder goodsOrderParam = new GoodsOrder();
					goodsOrderParam.setShopOrderCode(shopOrder.getCode());
					goodsOrderParam.setOrderState(OrderState.Create);
					List<GoodsOrder> goodsOrderList= goodsOrderDao.queryList(-1, -1, goodsOrderParam);
					if(goodsOrderList != null && goodsOrderList.size() > 0){
						for (GoodsOrder goodsOrder :goodsOrderList) {
							goodsOrder.setOrderState(OrderState.Cancel);
							goodsOrder.setCancelTime(purchaseOrder.getCancelTime());
							goodsOrderDao.modify(goodsOrder);
							//退卡券
							if(goodsOrder.getCardId()!=null){
								UserCards userCards=userCardsDao.getById(goodsOrder.getCardId());
								if(userCards!=null){
									returnUserCards(userCards);
								}
							}
							if(goodsOrder.getSeckill()){
								coreLogic.updateInventory(goodsOrder.getSeckillGoodsId(),FlowType.Add);
							}
						}
					}
				}
			}

			return true;
		}

	}
	//无条件取消
	public Boolean cancelOrder2(PurchaseOrder purchaseOrder,CancelReason cancelReason){
		if(purchaseOrder == null)
			return false;

		synchronized (purchaseOrder) {
			if (!OrderState.Create.equals(purchaseOrder.getOrderState()))
				return false;

			//修改一级订单状态
			purchaseOrder.setCancelReason(cancelReason);
			purchaseOrder.setOrderState(OrderState.Cancel);
			purchaseOrder.setCancelTime(new Date());
			purchaseOrderDao.modify(purchaseOrder);

			//修改二级订单状态
			ShopOrder shopOrderParam=new ShopOrder();
			shopOrderParam.setPurchaseOrderCode(purchaseOrder.getCode());
			List<ShopOrder> shopOrderList = shopOrderDao.queryList(-1, -1, shopOrderParam);
			if(shopOrderList != null && shopOrderList.size() > 0){
				for (ShopOrder shopOrder:shopOrderList){
					if(!OrderState.Create.equals(shopOrder.getOrderState()))
						continue;

					shopOrder.setOrderState(OrderState.Cancel);
					shopOrder.setCancelTime(purchaseOrder.getCancelTime());
					shopOrder.setCancelReason(cancelReason);
					shopOrderDao.modify(shopOrder);

					//修改三级订单状态
					GoodsOrder goodsOrderParam = new GoodsOrder();
					goodsOrderParam.setShopOrderCode(shopOrder.getCode());
					goodsOrderParam.setOrderState(OrderState.Create);
					List<GoodsOrder> goodsOrderList= goodsOrderDao.queryList(-1, -1, goodsOrderParam);
					if(goodsOrderList != null && goodsOrderList.size() > 0){
						for (GoodsOrder goodsOrder :goodsOrderList) {
							goodsOrder.setOrderState(OrderState.Cancel);
							goodsOrder.setCancelTime(purchaseOrder.getCancelTime());
							goodsOrderDao.modify(goodsOrder);
							//退卡券
							if(goodsOrder.getCardId()!=null){
								UserCards userCards=userCardsDao.getById(goodsOrder.getCardId());
								if(userCards!=null){
									returnUserCards(userCards);
								}
							}
							if(goodsOrder.getSeckill()){
								coreLogic.updateInventory(goodsOrder.getSeckillGoodsId(),FlowType.Add);
							}
						}
					}
				}
			}

			return true;
		}

	}
	//退还卡券
	public void  returnUserCards(UserCards userCards){
		if(userCards!=null){
			UserCards validCards=null;
			if(userCards.getGoodsId()!=null){
				validCards=userCardsDao.getByGoodsIdAndUserId(userCards.getGoodsId(),userCards.getUserId());
			}else {
				validCards=userCardsDao.getByGoodsCategoryIdAndUserId(userCards.getGoodsCategoryId(),userCards.getUserId());
			}
			if(validCards==null) {//用户已经没有 这样的一张有效的商品券或商品分类券
				if (userCards.getCardsState().equals(CardsState.Used)) {
					long nowTime = new Date().getTime();
					if (nowTime > userCards.getEndUseTime().getTime()) {//此时卡券已过期
						userCards.setCardsState(CardsState.Due);
					} else {//成功退还
						userCards.setCardsState(CardsState.Unused);
					}
					userCardsDao.modify(userCards);
				}
			}
		}
	}
	/**
	 * 支付之前取消
	 * ffl
	 * 2017-11-06 14:40:18
	 * @param token
	 * @param cancelReasonValue
	 * @param purchaseOrderId
	 * @return
	 */
	public String cancelOrder(String token,String cancelReasonValue,String purchaseOrderId){

		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(purchaseOrderId)){
			return CodeContent.getModelByCode(0,"请传入要取消的订单id",null);
		}
		PurchaseOrder purchaseOrder=purchaseOrderDao.getById(NumberUtils.toInt(purchaseOrderId));
		if(purchaseOrder==null){
			return CodeContent.getModelByCode(0,"未找到id为"+purchaseOrderId+"的购买订单",null);
		}
		if(purchaseOrder.getUserId()-user.getId()!=0){
			return CodeContent.getModelByCode(0,"id为"+purchaseOrderId+"的购买订单不是您的购买订单",null);
		}
		if(!NumberUtils.isDigits(cancelReasonValue)){
			return CodeContent.getModelByCode(0,"请传入取消的原因",null);
		}
		CancelReason cancelReason=CancelReason.getByIntValue(NumberUtils.toInt(cancelReasonValue));
		if(cancelReason==null){
			return CodeContent.getModelByCode(0,"请传入合法的取消的原因",null);
		}
		Boolean cancelResult=cancelOrder2(purchaseOrder,cancelReason);
		if(cancelResult){
			return CodeContent.getModelByCode(1,"",null);
		}else {
			return CodeContent.getModelByCode(0,"取消失败",null);
		}
	}

	/**
	 * 用户支付之后发货之前停止购买
	 * @return
	 */
	public boolean stopOrder(ShopOrder shopOrder,  CancelReason cancelReason,String handleDetail, User user){
		if(shopOrder==null || cancelReason== null ||user==null|| com.stlm2.util.StringUtils.isNullOrEmpty(handleDetail)){
			return false;
		}

		if (OrderState.Payment.equals(shopOrder.getOrderState()) ||OrderState.Delivery.equals(shopOrder.getOrderState())) {
			Date cancelTime=new Date();
			//修改二级订单
			shopOrder.setCancelReason(cancelReason);
			shopOrder.setCancelTime(cancelTime);
			shopOrder.setHandlerId(user.getId());
			shopOrder.setHandleDetail(handleDetail);
			shopOrder.setOrderState(OrderState.StopBuying);
			shopOrderDao.modify(shopOrder);
			//修改三级订单
			GoodsOrder goodsOrderParam=new GoodsOrder();
			goodsOrderParam.setShopOrderCode(shopOrder.getCode());
			List<GoodsOrder> goodsOrderList=goodsOrderDao.queryList(-1,-1,goodsOrderParam);
			if (goodsOrderList!=null&&goodsOrderList.size()>0){
				for ( GoodsOrder goodsOrder:goodsOrderList) {
					goodsOrder.setOrderState(OrderState.StopBuying);
					goodsOrder.setCancelTime(cancelTime);
					goodsOrderDao.modify(goodsOrder);
					//修改商品销量
					DdmGoods goods=ddmGoodsDao.getById(goodsOrder.getGoodsId());
					synchronized (goods) {
						if(goods.getSalesVolume()-goodsOrder.getNum()>=0) {
							goods.setSalesVolume(goods.getSalesVolume() - goodsOrder.getNum());
							ddmGoodsDao.modify(goods);
						}
					}
					//添加库存日志
					InventoryLog inventoryLog=new InventoryLog();
					inventoryLog.setChangeNum(goodsOrder.getNum());
					inventoryLog.setCreateTime(cancelTime);
					inventoryLog.setInventorySource(InventorySource.OrderCancel);
					inventoryLog.setType(FlowType.Add);
					inventoryLog.setUserId(goodsOrder.getUserId());
					inventoryLog.setCode(goodsOrder.getCode());
					inventoryLog.setRemark("放弃购买");
                    //回放库存
					Inventory inventory=inventoryDao.getOnlyInventory(shopOrder.getShopId(),goodsOrder.getGoodsId(),goodsOrder.getGoodsSpecificationId());
					if(inventory!=null) {
						synchronized (inventory) {
							inventory.setInventory(inventory.getInventory() + goodsOrder.getNum());
							inventoryDao.modify(inventory);
						}
						inventoryLog.setInventoryId(inventory.getId());
						inventoryLogDao.add(inventoryLog);
					}
					if(goodsOrder.getSeckill()){
						coreLogic.updateInventory(goodsOrder.getSeckillGoodsId(),FlowType.Add);
					}
					//退卡券
					if(goodsOrder.getCardId()!=null){
						UserCards userCards=userCardsDao.getById(goodsOrder.getCardId());
						if(userCards!=null){
							returnUserCards(userCards);
						}
					}
					//取消增值服务
					serviceOrderDao.updateState(goodsOrder.getCode());
				}

				//退还用户支付金额 添加资金流水
				coreLogic.addFundsFlow(user.getId(),shopOrder.getPayMoney(), FlowSource.StopBuying, FlowType.Add, shopOrder.getId(), shopOrder.getCode());
				coreLogic.changeMoneyAccount(user.getId(),shopOrder.getPayMoney(),FlowSource.StopBuying,FlowType.Add);
			}else {
				return false;
			}

		}else{
			return false;
		}
		return true;
	}


	/**
	 * 用户支付之后发货之前停止购买
	 * ffl
	 * 2017-11-06 14:30:17
	 * @param token
	 * @param shopOrderId
	 * @param cancelReasonValue
	 * @return
	 */
	public String stopOrder(String token,String shopOrderId,String cancelReasonValue){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(shopOrderId)){
			return CodeContent.getModelByCode(0,"请传入要取消的订单id",null);
		}
		ShopOrder shopOrder=shopOrderDao.getById(NumberUtils.toInt(shopOrderId));
		if(shopOrder==null){
			return CodeContent.getModelByCode(0,"未找到id为"+shopOrderId+"的购买订单",null);
		}
		if(shopOrder.getUserId()-user.getId()!=0){
			return CodeContent.getModelByCode(0,"id为"+shopOrderId+"的购买订单不是您的购买订单",null);
		}
		if(!NumberUtils.isDigits(cancelReasonValue)){
			return CodeContent.getModelByCode(0,"请传入取消的原因",null);
		}
		CancelReason cancelReason=CancelReason.getByIntValue(NumberUtils.toInt(cancelReasonValue));
		if(cancelReason==null){
			return CodeContent.getModelByCode(0,"请传入合法的取消的原因",null);
		}
		Boolean cancelResult=stopOrder(shopOrder,cancelReason,"放弃购买",user);
		if(cancelResult){
			return CodeContent.getModelByCode(1,"",null);
		}else {
			return CodeContent.getModelByCode(0,"取消失败",null);
		}


	}

	/**
	 * 用户订单
	 * ffl
	 * 2017-11-07 11:40:00
	 * @param token
	 * @param orderStateValue
	 * @param hasComment
	 * @param pageNum
	 * @return
	 */
	public String orderList(String token,String orderStateValue,String hasComment,String pageNum){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		int pageNo=1;
		if(NumberUtils.isDigits(pageNum)){
			pageNo=NumberUtils.toInt(pageNum);
		}else {
			return CodeContent.getModelByCode(0,"未传入查看订单页数",null);
		}
		PurchaseOrder param=new PurchaseOrder();

		if(NumberUtils.isDigits(orderStateValue)){
			if(NumberUtils.toInt(orderStateValue)==10){
				param.setHasComment(true);
			}else {
				param.setOrderStateValue(NumberUtils.toInt(orderStateValue));
			}

		}
		if ("ture".equals(hasComment)){
			param.setHasComment(true);
		}
		param.setUserId(user.getId());
		ModelMap model = new ModelMap();
		PageView pageView=purchaseOrderDao.queryPageView(pageNo,10,param);
		if (pageView != null) {
			model.put("purchaseOrders", convertPurchaseOrder(pageView.getRecords()));
			model.put("recordsTotal",pageView.getRowCount());
			model.put("totalPage", pageView.getPageCount());
		}
		model.put("pageNo", pageNo);
		model.put("code",1);
		model.put("msg","success");
		return new org.json.JSONObject(model).toString();
	}
    //购买订单
	public List<ModelMap> convertPurchaseOrder(List<PurchaseOrder> purchaseOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (purchaseOrderList != null && purchaseOrderList.size() > 0) {
			for (PurchaseOrder purchaseOrder: purchaseOrderList) {
				ModelMap map = buildModelPurchaseOrder(purchaseOrder);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelPurchaseOrder(PurchaseOrder purchaseOrder) {
		ModelMap model = new ModelMap();
		if (purchaseOrder!=null) {
			model.put("id", purchaseOrder.getId());
			model.put("code",purchaseOrder.getCode());
			model.put("orderState", purchaseOrder.getOrderState() != null ? purchaseOrder.getOrderState().toString() : "");
			model.put("orderStateValue", purchaseOrder.getOrderStateValue());
			model.put("createTime", purchaseOrder.getCreateTime() != null ? Convert.toFullYMDHMS(purchaseOrder.getCreateTime()) : "");
			model.put("payMoney", purchaseOrder.getPayMoney() != null ? purchaseOrder.getPayMoney() : "");
			ShopOrder shopOrderParam = new ShopOrder();
			shopOrderParam.setPurchaseOrderCode(purchaseOrder.getCode());
			List<ShopOrder> shopOrderList = shopOrderDao.queryList(-1, -1, shopOrderParam);
			if (shopOrderList != null && shopOrderList.size() > 0) {
				model.put("shopOrders", convertShopOrder(shopOrderList));
			}
			Integer goodsOrderNum=goodsOrderDao.countByPurchaseOrderCode(purchaseOrder.getCode());
			model.put("goodsOrderNum",goodsOrderNum);
			model.put("serviceNum",purchaseOrder.getServiceNum());
			Double serviceMoney=goodsOrderDao.sumByPurchaseOrderCode(purchaseOrder.getCode());
			model.put("serviceMoney",serviceMoney);
			model.put("payType",purchaseOrder.getPayType()!=null?purchaseOrder.getPayType().toString():"");
			model.put("deliveryType",purchaseOrder.getDeliveryType()!=null?purchaseOrder.getDeliveryType().toString():"");
			model.put("payTypeValue",purchaseOrder.getPayType()!=null?purchaseOrder.getPayTypeValue():"");
			model.put("deliveryTypeValue",purchaseOrder.getDeliveryType()!=null?purchaseOrder.getDeliveryTypeValue():"");
		}
		return  model;
	}
	//拆分的店铺仓库订单
	public List<ModelMap> convertShopOrder(List<ShopOrder> shopOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (shopOrderList!= null && shopOrderList.size() > 0) {
			for (ShopOrder shopOrder: shopOrderList) {
				ModelMap map = buildModelShopOrder(shopOrder);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelShopOrder(ShopOrder shopOrder) {
		ModelMap model = new ModelMap();
		if (shopOrder!=null) {
			model.put("id", shopOrder.getId());
			model.put("code",shopOrder.getCode());
			model.put("orderState", shopOrder.getOrderState() != null ? shopOrder.getOrderState().toString() : "");
			model.put("orderStateValue", shopOrder.getOrderStateValue());
			model.put("createTime", shopOrder.getCreateTime() != null ? Convert.toFullYMDHMS(shopOrder.getCreateTime()) : "");
			model.put("payMoney", shopOrder.getPayMoney() != null ? shopOrder.getPayMoney() : "");
			String shopName="叮当网";
			DdmShop shop=ddmShopDao.getById(shopOrder.getShopId());
			if(shop!=null){
				shopName=shop.getName();
			}
			model.put("shopName",shopName);
			model.put("hasComment",shopOrder.getHasComment()!=null?shopOrder.getHasComment():false);
			List<GoodsOrder> goodsOrderList=goodsOrderDao.getByShopOrderCode(shopOrder.getCode());
			if (goodsOrderList != null && goodsOrderList.size() > 0) {
				model.put("goodsOrders", convertGoodsOrder(goodsOrderList));
			}
			model.put("express",shopOrder.getExpressType()!=null?shopOrder.getExpressType().toString():"");
			model.put("expressTypeValue",shopOrder.getExpressTypeValue()!=null?shopOrder.getExpressTypeValue():"");
			if(shopOrder.getExpressTypeValue()!=null){
				model.put("expressCompany",ExpressCompany.getByIntValue(shopOrder.getExpressTypeValue())!=null?ExpressCompany.getByIntValue(shopOrder.getExpressTypeValue()).toString():"");
			}else {
				model.put("expressCompany","");
			}
			model.put("wayBillNum",shopOrder.getWayBillNum()!= null ? shopOrder.getWayBillNum() : "");
			model.put("serviceNum",shopOrder.getServiceNum());
			Double serviceMoney=goodsOrderDao.sumByShopOrderCode(shopOrder.getCode());
			model.put("serviceMoney",serviceMoney);
		}
		return  model;
	}
    //订单详情
	public List<ModelMap> convertGoodsOrder(List<GoodsOrder> goodsOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (goodsOrderList != null && goodsOrderList.size() > 0) {
			for (GoodsOrder goodsOrder : goodsOrderList) {
				ModelMap map = buildModelGoodsOrder(goodsOrder);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModelGoodsOrder(GoodsOrder goodsOrder) {
		ModelMap model = new ModelMap();
		if (goodsOrder!= null) {
			model.put("id", goodsOrder.getId());
			model.put("code", goodsOrder.getCode());
			model.put("hasComment", goodsOrder.getHasComment()!=null?goodsOrder.getHasComment():false);
			model.put("orderState", goodsOrder.getOrderState() != null ? goodsOrder.getOrderState().toString() : "");
			model.put("orderStateValue", goodsOrder.getOrderStateValue());
			model.put("goodsId", goodsOrder.getGoodsId());
			model.put("goodsName", goodsOrder.getGoodsName());
			model.put("payMoney", goodsOrder.getPayMoney() != null ? goodsOrder.getPayMoney() : "");
			DdmGoods goods = ddmGoodsDao.getById(goodsOrder.getGoodsId());
			String goodsImg="";
			if (goods != null) {
				String [] mainImg=goods.getMainImg().split(",");
				goodsImg=mainImg[0];
			}

			String specificationName="";
			if(goodsOrder.getGoodsSpecificationId()!=null){
				GoodSpecification goodSpecification=goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
				if(goodSpecification!=null){
					specificationName=goodSpecification.getPropertiesName();
					goodsImg=goodSpecification.getImage();
				}
			}
			model.put("goodsImg", goodsImg);
			model.put("specificationName",specificationName);
			model.put("unitPrice", goodsOrder.getSalePrice());
			model.put("num", goodsOrder.getNum());
			model.put("serviceNum",goodsOrder.getServiceNum());
			model.put("serviceMoney",goodsOrder.getServiceMoney());
		}
		return model;
	}

	/**
	 * 订单详情
	 * ffl
	 * 2017-11-07 16:16:42
	 * @param token
	 * @param shopOrderId
	 * @return
	 */
	public String orderDetail(String token,String shopOrderId){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(!NumberUtils.isDigits(shopOrderId)){
			return CodeContent.getModelByCode(0,"未传入店铺订单id",null);
		}
		ShopOrder shopOrder=shopOrderDao.getById(NumberUtils.toInt(shopOrderId));
		if(shopOrder==null){
			return CodeContent.getModelByCode(0,"未找到订单",null);
		}
		PurchaseOrder purchaseOrder=purchaseOrderDao.getByCode(shopOrder.getPurchaseOrderCode());
		if(purchaseOrder==null){
			return CodeContent.getModelByCode(0,"未找到购买订单",null);
		}
		ModelMap model=new ModelMap();
		model.put("deliveryAddress",buildModelAddress(purchaseOrder));
		model.put("shopOrder",buildModelShopOrderDetail(shopOrder));
        model.put("msg","success");
        model.put("code",1);
		return new JSONObject(model).toString();
	}

	public ModelMap buildModelAddress(PurchaseOrder purchaseOrder) {
		ModelMap model = new ModelMap();
		if (purchaseOrder!= null) {
			model.put("purchaseOrderId", purchaseOrder.getId());
			model.put("code", purchaseOrder.getCode());
			model.put("payMoney",purchaseOrder.getPayMoney());
			model.put("userName", purchaseOrder.getName()!= null ? purchaseOrder.getName() : "");
			model.put("addressDetail", purchaseOrder.getAddressDetail() != null ? purchaseOrder.getAddressDetail() : "");
			model.put("city", purchaseOrder.getCity() != null ? purchaseOrder.getCity() : "");
			model.put("phone", purchaseOrder.getPhone()!= null ? purchaseOrder.getPhone() : "");
		}
		return model;
	}
	public ModelMap buildModelShopOrderDetail(ShopOrder shopOrder) {
		ModelMap model = new ModelMap();
		if (shopOrder!=null) {
			model.put("id", shopOrder.getId());
			model.put("code",shopOrder.getCode());
			model.put("orderState", shopOrder.getOrderState() != null ? shopOrder.getOrderState().toString() : "");
			model.put("orderStateValue", shopOrder.getOrderStateValue());
			model.put("createTime", shopOrder.getCreateTime() != null ? Convert.toFullYMDHMS(shopOrder.getCreateTime()) : "");
			model.put("payMoney", shopOrder.getPayMoney() != null ? shopOrder.getPayMoney() : "");
			model.put("payType",shopOrder.getPayType()!=null?shopOrder.getPayType().toString():"");
			model.put("deliveryType",shopOrder.getDeliveryType()!=null?shopOrder.getDeliveryType().toString():"");
			model.put("payTypeValue",shopOrder.getPayType()!=null?shopOrder.getPayTypeValue():"");
			model.put("deliveryTypeValue",shopOrder.getDeliveryType()!=null?shopOrder.getDeliveryTypeValue():"");
			model.put("express",shopOrder.getExpressType()!=null?shopOrder.getExpressType().toString():"");
			model.put("expressTypeValue",shopOrder.getExpressTypeValue()!=null?shopOrder.getExpressTypeValue():"");
			if(shopOrder.getExpressTypeValue()!=null){
				model.put("expressCompany",ExpressCompany.getByIntValue(shopOrder.getExpressTypeValue())!=null?ExpressCompany.getByIntValue(shopOrder.getExpressTypeValue()).toString():"");
			}else {
				model.put("expressCompany","");
			}
			model.put("wayBillNum",shopOrder.getWayBillNum()!= null ? shopOrder.getWayBillNum() : "");
			String shopName="叮当网";
			String shopPhone="";
			String shopMan="";
			String shopLocation="";
			DdmShop shop=ddmShopDao.getById(shopOrder.getShopId());
			if(shop!=null){
				shopName=shop.getName();
				shopPhone=shop.getContact();
				shopMan=shop.getLinkman();
				shopLocation=shop.getLocation();
			}
			model.put("shopPhone",shopPhone);
			model.put("shopMan",shopMan);
			model.put("shopLocation",shopLocation);
			model.put("hasComment",shopOrder.getHasComment()!=null?shopOrder.getHasComment():false);
			model.put("nowTime",new Date().getTime());
			model.put("timeDif",shopOrder.getCreateTime().getTime()+86400000-new Date().getTime());
			model.put("shopName",shopName);
			List<GoodsOrder> goodsOrderList=goodsOrderDao.getByShopOrderCode(shopOrder.getCode());
			if (goodsOrderList != null && goodsOrderList.size() > 0) {
				model.put("goodsOrders", convertGoodsOrderDetail(goodsOrderList));
			}
		}
		return  model;
	}
	public List<ModelMap> convertGoodsOrderDetail(List<GoodsOrder> goodsOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (goodsOrderList != null && goodsOrderList.size() > 0) {
			for (GoodsOrder goodsOrder : goodsOrderList) {
				ModelMap map = buildModelGoodsOrderDetail(goodsOrder);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModelGoodsOrderDetail(GoodsOrder goodsOrder) {
		ModelMap model = new ModelMap();
		if (goodsOrder!= null) {
			model.put("id", goodsOrder.getId());
			model.put("code", goodsOrder.getCode());
			model.put("hasComment", goodsOrder.getHasComment()!=null?goodsOrder.getHasComment():false);
			model.put("orderState", goodsOrder.getOrderState() != null ? goodsOrder.getOrderState().toString() : "");
			model.put("orderStateValue", goodsOrder.getOrderStateValue());
			model.put("totalMoney", goodsOrder.getTotalMoney() != null ? goodsOrder.getTotalMoney() : "");
			model.put("payMoney",goodsOrder.getPayMoney()!=null?goodsOrder.getPayMoney():"");
			model.put("saveMoney",goodsOrder.getSaveMoney()!=null ?goodsOrder.getSaveMoney():"");
			model.put("goodsId", goodsOrder.getGoodsId());
			model.put("goodsName", goodsOrder.getGoodsName());
			DdmGoods goods = ddmGoodsDao.getById(goodsOrder.getGoodsId());
			String goodsImg="";
			if (goods != null) {
				String [] mainImg=goods.getMainImg().split(",");
				goodsImg=mainImg[0];
			}
			model.put("goodsImg", goodsImg);
			String specificationName="";
			if(goodsOrder.getGoodsSpecificationId()!=null){
				GoodSpecification goodSpecification=goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
				if(goodSpecification!=null){
					specificationName=goodSpecification.getPropertiesName();
				}
			}
			model.put("goodsLmie",goodsOrder.getIdentifyCode()!=null?goodsOrder.getIdentifyCode():"");
			model.put("hasLmie",goodsOrder.getHasLmie()!=null?goodsOrder.getHasLmie():false);
			Boolean hasLmie=goodsOrder.getHasLmie()!=null?goodsOrder.getHasLmie():false;
			String ifHas="无";
			if(hasLmie){
				ifHas="有";
			}
			model.put("ifHas",ifHas);
			model.put("specificationName",specificationName);
			model.put("unitPrice", goodsOrder.getSalePrice());
			model.put("num", goodsOrder.getNum());
			model.put("serviceMoney",goodsOrder.getServiceMoney()!=null?goodsOrder.getServiceMoney():0);
			model.put("serviceNum",goodsOrder.getServiceNum()!=null?goodsOrder.getServiceNum():0);
			model.put("serviceOrders",convertServiceIds(goodsOrder.getAddServiceId()));
		}
		return model;
	}
	public List<ModelMap> convertServiceOrder(List<ServiceOrder> serviceOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (serviceOrderList != null && serviceOrderList.size() > 0) {
			for (ServiceOrder serviceOrder : serviceOrderList) {
				ModelMap map = buildModelServiceOrder(serviceOrder);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModelServiceOrder(ServiceOrder serviceOrder) {
		ModelMap model = new ModelMap();
		if (serviceOrder!= null) {
			ValueAddedServices valueAddedServices=valueAddedServicesDao.getById(serviceOrder.getId());
			model.put("name",valueAddedServices.getName());
			model.put("id", serviceOrder.getId());
			model.put("state",serviceOrder.getState());
			model.put("num",serviceOrder.getNum());
			model.put("createTime", Convert.toShortYMD(serviceOrder.getCreateTime()));
			model.put("endTime",Convert.toShortYMD(serviceOrder.getEndTime()));
			model.put("imie",serviceOrder.getImie()!=null?serviceOrder.getImie():"");
		}
		return model;
	}


	public List<ModelMap> convertServiceIds(String serviceIds) {
		List<String>serviceIdList=new ArrayList<String>();
		if(serviceIds!=null){
			String []service=serviceIds.split(",");
			for (int i=0;i<service.length;i++){
				serviceIdList.add(service[i]);
			}
		}
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (serviceIdList != null && serviceIdList.size() > 0) {
			for (String serviceId : serviceIdList) {
				ModelMap map = buildModelServiceIds(serviceId);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModelServiceIds(String serviceId) {
		ModelMap model = new ModelMap();
		if (NumberUtils.isDigits(serviceId)) {
			ValueAddedServices valueAddedServices=valueAddedServicesDao.getById(NumberUtils.toInt(serviceId));
			model.put("id",valueAddedServices.getId());
			model.put("name",valueAddedServices.getName());
			model.put("price",valueAddedServices.getPrice() + "元");
			model.put("warrantyPeriod",valueAddedServices.getWarrantyPeriod()+"个月");
			model.put("valueAddedServicesType",valueAddedServices.getValueAddedServicesType().toString());
			model.put("valueAddedServicesKind",valueAddedServices.getValueAddedServicesKind().toString());
			model.put("next",valueAddedServices.getNext()!=null?valueAddedServices.getNext()+"次":"");
			model.put("detailsUrl",valueAddedServices.getDetailsUrl()!=null?valueAddedServices.getDetailsUrl():"");
			model.put("label",valueAddedServices.getLabel());
			model.put("state",valueAddedServices.getState()?"有效":"无效");

		}
		return model;
	}



	/**
	 *  确认收货
	 * ffl
	 * 2017-11-08 11:47:05
	 * @param shopOrder
	 * @return
	 */
	public Boolean confirmReceiptOrder(ShopOrder shopOrder){
		if (shopOrder == null )
			return false;

		synchronized (shopOrder) {
			if (!OrderState.Deliveried.equals(shopOrder.getOrderState()))
				return false;

			//修改二级订单状态
			shopOrder.setOrderState(OrderState.Receipt);
			shopOrder.setReceiptTime(new Date());
			Boolean hasComment=shopOrder.getHasComment()!=null?shopOrder.getHasComment():true;
			if(hasComment) {
				shopOrder.setHasComment(true);
			}
			shopOrderDao.modify(shopOrder);
			//修改三级订单状态
			List<GoodsOrder> goodsOrderList = goodsOrderDao.getByShopOrderCode(shopOrder.getCode());
			if (goodsOrderList != null && goodsOrderList.size() > 0 ){
				for (GoodsOrder goodsOrder : goodsOrderList) {
					if (!OrderState.Deliveried.equals(goodsOrder.getOrderState()))
						continue;
					goodsOrder.setOrderState(OrderState.Receipt);
					goodsOrder.setHasComment(hasComment);
					goodsOrder.setReceiptTime(new Date());
					goodsOrderDao.modify(goodsOrder);
				}
			}
			//赠送积分
			if(shopOrder.getPayMoney().compareTo(new BigDecimal(0))==1){
				BigDecimal integral=shopOrder.getPayMoney().multiply(new BigDecimal(0.01));

				//添加积分
				Account account=accountDao.getByUserId(shopOrder.getUserId());
				account.setRemainJiFen(account.getRemainJiFen().add(integral));
				account.setTotalJiFen(account.getTotalJiFen().add(integral));
				accountDao.modify(account);

				//添加积分流水
				coreLogic.addFundsFlow(shopOrder.getUserId(),integral, FlowSource.GiveIntegral, FlowType.Add, shopOrder.getId(), shopOrder.getCode());
			}
			return true;
		}
	}

	/**
	 * 定时任务
	 * 发货七天后 自动确认收货
	 * ffl
	 * 2017-11-08 13:58:11
	 */
	public void confirmReceiptOrder(){
		ShopOrder param=new ShopOrder();
		param.setReceiptEndTime(new Date());
		param.setOrderState(OrderState.Deliveried);
		List<ShopOrder> shopOrderList=shopOrderDao.queryList(-1,-1,param);
		if(shopOrderList!=null&&shopOrderList.size()>0) {
			for (ShopOrder shopOrder : shopOrderList) {
				confirmReceiptOrder(shopOrder);
			}
		}
	}


	/**
	 * 确认收货  接口
	 * ffl
	 * 2017-11-08 20:22:48
	 * @param token
	 * @param shopOrderId
	 * @return
	 */
	public String confirmReceiptOrder(String token,String shopOrderId){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(shopOrderId)){
			return CodeContent.getModelByCode(0,"未传入合法的订单id",null);
		}
		ShopOrder shopOrder=shopOrderDao.getById(NumberUtils.toInt(shopOrderId));
		if(shopOrder==null){
			return CodeContent.getModelByCode(0,"未找到购买订单",null);
		}
		Boolean result=confirmReceiptOrder(shopOrder);
		if(result){
			return CodeContent.getModelByCode(1,"",null);
		}else {
			return CodeContent.getModelByCode(0,"确认收货失败",null);
		}


	}


	/**
	 * 订单状态下的 订单数量
	 * ffl
	 * 2017-11-09 11:04:24
	 * @param token

	 * @return
	 */
	public String  purchaseOrderNum(String token){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		//获得用户待付款的订单数量
		int createNum = purchaseOrderDao.purchaseOrderNum(user.getId(),1);
		//获得用户待发货的订单数量
		int paymentNum = purchaseOrderDao.purchaseOrderNum(user.getId(),3);
		//获得用户待收货的订单数量
		int deliveriedNum = purchaseOrderDao.purchaseOrderNum(user.getId(),5);
		//获得用户待评价的订单数量
		int commentNum = purchaseOrderDao.purchaseOrderNum2(user.getId());
		ModelMap model=new ModelMap();

		model.put("createNum", createNum);
		model.put("paymentNum", paymentNum);
		model.put("deliveriedNum", deliveriedNum);
		model.put("commentNum", commentNum);
		model.put("code",1);
		model.put("msg","success");
		return new JSONObject(model).toString();
	}


	/**
	 * 去评价 展示商品
	 * ffl
	 * 2017-11-09 17:30:57
	 * @param token
	 * @param shopOrderId
	 * @return
	 */
	public String orderComment(String token,String shopOrderId){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(!NumberUtils.isDigits(shopOrderId)){
			return CodeContent.getModelByCode(0,"未传入店铺订单id",null);
		}
		ShopOrder shopOrder=shopOrderDao.getById(NumberUtils.toInt(shopOrderId));
		if(shopOrder==null){
			return CodeContent.getModelByCode(0,"未找到订单",null);
		}

		ModelMap model=new ModelMap();
		List<GoodsOrder> goodsOrderList=goodsOrderDao.getByShopOrderCode(shopOrder.getCode());
		model.put("goodsList",convertGoodsOrderComment(goodsOrderList));
		model.put("shopOrderId",shopOrderId);
		return CodeContent.getModelByCode(1,"",model);
	}
	public List<ModelMap> convertGoodsOrderComment(List<GoodsOrder> goodsOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (goodsOrderList != null && goodsOrderList.size() > 0) {
			for (GoodsOrder goodsOrder : goodsOrderList) {
				ModelMap map = buildModelGoodsOrderComment(goodsOrder);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModelGoodsOrderComment(GoodsOrder goodsOrder) {
		ModelMap model = new ModelMap();
		if (goodsOrder!= null) {
			model.put("id",goodsOrder.getId());
			model.put("goodsId", goodsOrder.getGoodsId());
			model.put("goodsName", goodsOrder.getGoodsName());
			DdmGoods goods = ddmGoodsDao.getById(goodsOrder.getGoodsId());
			String goodsImg="";
			if (goods != null) {
				goodsImg=goods.getMainImg();
			}
			model.put("goodsImg", goodsImg);
			String specificationName="";
			if(goodsOrder.getGoodsSpecificationId()!=null){
				GoodSpecification goodSpecification=goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
				if(goodSpecification!=null){
					specificationName=goodSpecification.getPropertiesName();
				}
			}
			model.put("specificationName",specificationName);
		}
		return model;
	}

	/**
	 * 退款详情
	 * ffl
	 * 2017-11-10 14:18:57
	 * @param token
	 * @param goodsOrderId
	 * @return
	 */
	public String refundDetail(String token,String goodsOrderId){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(!NumberUtils.isDigits( goodsOrderId)){
			return CodeContent.getModelByCode(0,"未传入商品订单id",null);
		}
		GoodsOrder goodsOrder=goodsOrderDao.getById(NumberUtils.toInt(goodsOrderId));
		if(goodsOrder==null){
			return CodeContent.getModelByCode(0,"未找到商品订单",null);
		}
		RefundLog refundLog=refundLogDao.getByGoodsOrderId(goodsOrder.getId());
		if(refundLog==null){
			return CodeContent.getModelByCode(0,"未找到商品订单的退款信息",null);
		}
		PurchaseOrder purchaseOrder=purchaseOrderDao.getByCode(goodsOrder.getPurchaseOrderCode());
		if(purchaseOrder==null){
			return CodeContent.getModelByCode(0,"未找到商品订单的退款信息",null);
		}
		ModelMap model=new ModelMap();
		model.put("address",buildModelAddress(purchaseOrder));
		model.put("goods",buildModelGoodsOrderRefund(goodsOrder));
		model.put("serviceOrder",convertServiceIds(goodsOrder.getAddServiceId()));
		model.put("refundLog",buildModelRefund(refundLog));
		return CodeContent.getModelByCode(1,"",model);
	}

	public ModelMap buildModelGoodsOrderRefund(GoodsOrder goodsOrder) {
		ModelMap model = new ModelMap();
		if (goodsOrder!= null) {
			model.put("id", goodsOrder.getId());
			model.put("code", goodsOrder.getCode());
			model.put("orderState", goodsOrder.getOrderState() != null ? goodsOrder.getOrderState().toString() : "");
			model.put("orderStateValue", goodsOrder.getOrderStateValue());
			model.put("goodsId", goodsOrder.getGoodsId());
			model.put("goodsName", goodsOrder.getGoodsName());
			DdmGoods goods = ddmGoodsDao.getById(goodsOrder.getGoodsId());
			String goodsImg="";
			if (goods != null) {
				goodsImg=goods.getMainImg();
			}
			model.put("goodsImg", goodsImg);
			model.put("goodsNum",goodsOrder.getNum());
			model.put("unitPrice",goodsOrder.getSalePrice());
			String specificationName="";
			if(goodsOrder.getGoodsSpecificationId()!=null){
				GoodSpecification goodSpecification=goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
				if(goodSpecification!=null){
					specificationName=goodSpecification.getPropertiesName();
				}
			}
			model.put("specificationName",specificationName);
		}
		return model;
	}
	public ModelMap buildModelRefund(RefundLog refundLog) {
		ModelMap model = new ModelMap();
		if (refundLog!= null) {
			model.put("id", refundLog.getId());
			model.put("code", refundLog.getCode());
			model.put("refundState", refundLog.getRefundState() != null ?refundLog.getRefundState().toString() : "");
			model.put("refundStateValue", refundLog.getRefundStateValue());
			model.put("refundType", refundLog.getRefundType() != null ?refundLog.getRefundType().toString() : "");
			model.put("refundTypeValue", refundLog.getRefundTypeValue());
			model.put("refundReasonValue",refundLog.getRefundReasonValue());
			model.put("refundReason",refundLog.getRefundReason()!=null ? refundLog.getRefundReason().toString():"");
			model.put("num", refundLog.getNum());
			model.put("refundMoney", refundLog.getTotalMoney());
			model.put("refundExplain", refundLog.getRefundExplain());
			model.put("createTime",Convert.toFullYMDHMS(refundLog.getCreateTime()));
			model.put("handleTime",refundLog.getHandleTime()!=null?Convert.toFullYMDHMS(refundLog.getCreateTime()):"");
		}
		return model;
	}

	/**
	 * 退款/售后 列表
	 * ffl
	 * 2017-11-11 19:35:45
	 * @param token
	 * @param pageNum
	 * @return
	 */
	public String refundList(String token,String pageNum){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		int pageNo=1;
		if(NumberUtils.isDigits(pageNum)){
			pageNo=NumberUtils.toInt(pageNum);
		}else {
			return CodeContent.getModelByCode(0,"未传入查看页数",null);
		}
		RefundLog refundLog=new RefundLog();
		refundLog.setUserId(user.getId());
		PageView pageView=refundLogDao.queryPageView(pageNo,10,refundLog);
		ModelMap model = new ModelMap();
		if (pageView != null) {
			model.put("refundList", convertRefundLog(pageView.getRecords()));
			model.put("recordsTotal",pageView.getRowCount());
			model.put("totalPage", pageView.getPageCount());
		}
		model.put("pageNo", pageNo);
		model.put("code",1);
		model.put("msg","success");
		return new org.json.JSONObject(model).toString();

	}

	public List<ModelMap> convertRefundLog(List<RefundLog> refundLogList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if ( refundLogList != null &&  refundLogList.size() > 0) {
			for (RefundLog refundLog :  refundLogList) {
				ModelMap map = buildModelRefundLog(refundLog);
				list.add(map);
			}
		}

		return list;
	}
	public ModelMap buildModelRefundLog(RefundLog refundLog) {
		ModelMap model = new ModelMap();
		if (refundLog!= null) {
			model.put("id", refundLog.getId());
			model.put("code", refundLog.getCode());
			model.put("refundState", refundLog.getRefundState() != null ?refundLog.getRefundState().toString() : "");
			model.put("refundStateValue", refundLog.getRefundStateValue());
			model.put("refundType", refundLog.getRefundType() != null ?refundLog.getRefundType().toString() : "");
			model.put("refundTypeValue", refundLog.getRefundTypeValue());
			model.put("goodsOrderId",refundLog.getGoodsOrderId());
			GoodsOrder goodsOrder=goodsOrderDao.getById(refundLog.getGoodsOrderId());
			ShopOrder shopOrder =shopOrderDao.getById(refundLog.getShopOrderId());
			String shopName="叮当网";
			String goodsName="";
			String goodsImg="";
			String specificationName="";
			if(shopOrder!=null){
				DdmShop shop =ddmShopDao.getById(shopOrder.getShopId());
				if(shop!=null){
					shopName=shop.getName();
				}
			}
			if(goodsOrder!=null){
				DdmGoods goods=ddmGoodsDao.getById(goodsOrder.getGoodsId());
				if(goods!=null){
					goodsName=goods.getName();
					goodsImg=goods.getMainImg();
				}
				if(goodsOrder.getGoodsSpecificationId()!=null){
					GoodSpecification goodSpecification=goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
					if(goodSpecification!=null){
						specificationName=goodSpecification.getPropertiesName();
					}
				}
			}

			model.put("goodsImg",goodsImg);
			model.put("goodsName",goodsName);
			model.put("specificationName",specificationName);
			model.put("shopName",shopName);

		}
		return model;
	}



	//=============================                     CRM                  ============================================//

	/**
	 * 后台订单 查询
	 * 2017-11-11 16:32:45
	 * ffl
	 * @param token
	 * @param shopId 店铺或仓库id
	 * @param userName 用户账号 手机号
	 * @param realName 用户姓名
	 * @param payTypeValue 支付方式 1网上支付 2到店支付 3银行转账 4分期付款
	 * @param deliveryTypeValue 配送方式 1到店自取 2送货上门
	 * @param orderStateValue 订单状态值 1创建订单 2已取消 3已支付 4待发货 5已发货 6已完成 7已退款 10确认收货 11驳回订单 12退款申请 13放弃购买
	 * @param purchaseOrderCode 购买订单编码
	 * @param code 订单编码
	 * @param wayBillNum 物流单号
	 * @param pageNum 查询页数
	 * @return
	 */

	public String search(String token,String shopId,String userName,String realName,String payTypeValue,String deliveryTypeValue,String orderStateValue, String purchaseOrderCode ,String code,String wayBillNum,String pageNum){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		int pageNo=1;
		if(NumberUtils.isDigits(pageNum)){
			pageNo=NumberUtils.toInt(pageNum);
		}else {
			return CodeContent.getModelByCode(0,"未传入查询页数",null);
		}
		ShopOrder orderParam=new ShopOrder();
		if (NumberUtils.isDigits(shopId)){
			orderParam.setShopId(NumberUtils.toInt(shopId));
		}
		if(!com.stlm2.util.StringUtils.isNullOrEmpty(userName)){
			orderParam.setUserName(userName);
		}
		if(!com.stlm2.util.StringUtils.isNullOrEmpty(realName)){
			orderParam.setCnName(realName);
		}
		if (NumberUtils.isDigits(payTypeValue)){
			orderParam.setPayTypeValue(NumberUtils.toInt(payTypeValue));
		}

		if (NumberUtils.isDigits(deliveryTypeValue)){
			orderParam.setDeliveryTypeValue(NumberUtils.toInt(deliveryTypeValue));
		}

		if (NumberUtils.isDigits(orderStateValue)){
			orderParam.setOrderStateValue(NumberUtils.toInt(orderStateValue));
		}

		if(!com.stlm2.util.StringUtils.isNullOrEmpty(purchaseOrderCode)){
			orderParam.setPurchaseOrderCode(purchaseOrderCode);
		}
		if(!com.stlm2.util.StringUtils.isNullOrEmpty(code)){
			orderParam.setCode(code);
		}
		if(!com.stlm2.util.StringUtils.isNullOrEmpty(wayBillNum)){
			orderParam.setWayBillNum(wayBillNum);
		}

		PageView pageView=shopOrderDao.queryPageView(pageNo,10,orderParam);
		ModelMap model = new ModelMap();
		if (pageView != null) {
			model.put("shopOrderList", convertShopOrderCrm(pageView.getRecords()));
			model.put("recordsTotal",pageView.getRowCount());
			model.put("totalPage", pageView.getPageCount());
		}
		model.put("pageNo", pageNo);
		model.put("code",1);
		model.put("msg","success");
		return new org.json.JSONObject(model).toString();
	}

	public List<ModelMap> convertShopOrderCrm(List<ShopOrder> shopOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (shopOrderList!= null && shopOrderList.size() > 0) {
			for (ShopOrder shopOrder: shopOrderList) {
				ModelMap map = buildModelShopOrderCrm(shopOrder);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelShopOrderCrm(ShopOrder shopOrder) {
		ModelMap model = new ModelMap();
		if (shopOrder!=null) {
			model.put("id", shopOrder.getId());
			model.put("code",shopOrder.getCode());
			model.put("purchaseOrderCode",shopOrder.getPurchaseOrderCode());
			model.put("orderState", shopOrder.getOrderState() != null ? shopOrder.getOrderState().toString() : "");
			model.put("createTime", shopOrder.getCreateTime() != null ? Convert.toFullYMDHMS(shopOrder.getCreateTime()) : "");
			model.put("payMoney", shopOrder.getPayMoney() != null ? shopOrder.getPayMoney() : "");
			model.put("payType",shopOrder.getPayType()!=null?shopOrder.getPayType().toString():"");
			model.put("deliveryType",shopOrder.getDeliveryType()!=null?shopOrder.getDeliveryType().toString():"");
			PurchaseOrder purchaseOrder=purchaseOrderDao.getByCode(shopOrder.getPurchaseOrderCode());
			model.put("userName",purchaseOrder.getName()!=null?purchaseOrder.getName():"");
			model.put("phone",purchaseOrder.getPhone()!=null?purchaseOrder.getPhone():"");
			model.put("addressDetail",purchaseOrder.getAddressDetail()!=null?purchaseOrder.getAddressDetail():"");
			model.put("city",purchaseOrder.getCity()!=null?purchaseOrder.getCity():"");
			model.put("wayBillNum",shopOrder.getWayBillNum()!= null ? shopOrder.getWayBillNum() : "");
			model.put("payTime", shopOrder.getPayTime() != null ? Convert.toFullYMDHMS(shopOrder.getPayTime()) : "");
			String shopName="叮当网";
//			String shopPhone="";
//			String shopMan="";
//			String shopLocation="";
			DdmShop shop=ddmShopDao.getById(shopOrder.getShopId());
			if(shop!=null){
				shopName=shop.getName();
//				shopPhone=shop.getContact();
//				shopMan=shop.getLinkman();
//				shopLocation=shop.getLocation();
			}
//			model.put("shopPhone",shopPhone);
//			model.put("shopMan",shopMan);
//			model.put("shopLocation",shopLocation);
//			model.put("hasComment",shopOrder.getHasComment()!=null?shopOrder.getHasComment():false);
			model.put("shopName",shopName);

			User user=userDao.getById(shopOrder.getUserId());
			String userPhone="";
			String realName="";
			if(user!=null){
				userPhone=user.getName();
				realName=user.getRealName();
			}
			model.put("realName",realName);
			model.put("userPhone",userPhone);
		}
		return  model;
	}

	/**
	 * crm 获取订单详细信息
	 * ffl
	 * 2017-11-12 09:12:28
	 * @param token
	 * @param id
	 * @return
	 */
	public String getByShopOrderId(String token,String id){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}

		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入订单id",null);
		}
		ShopOrder shopOrder=shopOrderDao.getById(NumberUtils.toInt(id));
		if(shopOrder==null){
			return CodeContent.getModelByCode(0,"未找到订单",null);
		}
		return CodeContent.getModelByCode(1,"",buildModelShopOrderCrmDetail(shopOrder));
	}
    //crm订单详情
	public ModelMap buildModelShopOrderCrmDetail(ShopOrder shopOrder) {
		ModelMap model = new ModelMap();
		if (shopOrder!=null) {
			model.put("id", shopOrder.getId());
			model.put("code",shopOrder.getCode());
			model.put("purchaseOrderCode",shopOrder.getPurchaseOrderCode());
			model.put("orderState", shopOrder.getOrderState() != null ? shopOrder.getOrderState().toString() : "");
			model.put("orderStateValue", shopOrder.getOrderStateValue()!= null ? shopOrder.getOrderStateValue() : "");
			model.put("createTime", shopOrder.getCreateTime() != null ? Convert.toFullYMDHMS(shopOrder.getCreateTime()) : "");
			model.put("cancelTime", shopOrder.getCancelTime() != null ? Convert.toFullYMDHMS(shopOrder.getCancelTime()) : "");
			model.put("payTime", shopOrder.getPayTime() != null ? Convert.toFullYMDHMS(shopOrder.getPayTime()) : "");
			model.put("deliverTime", shopOrder.getDeliverTime() != null ? Convert.toFullYMDHMS(shopOrder.getDeliverTime() ) : "");
			model.put("receiptTime", shopOrder.getReceiptTime() != null ? Convert.toFullYMDHMS(shopOrder.getReceiptTime()) : "");
			model.put("payMoney", shopOrder.getPayMoney() != null ? shopOrder.getPayMoney() : "");
			model.put("payType",shopOrder.getPayType()!=null?shopOrder.getPayType().toString():"");
			model.put("deliveryType",shopOrder.getDeliveryType()!=null?shopOrder.getDeliveryType().toString():"");
			model.put("deliveryTypeValue",shopOrder.getDeliveryType()!=null?shopOrder.getDeliveryTypeValue():"");
			model.put("serviceNum",shopOrder.getServiceNum());
			Double serviceMoney=goodsOrderDao.sumByShopOrderCode(shopOrder.getCode());
			model.put("serviceMoney",serviceMoney);
			PurchaseOrder purchaseOrder=purchaseOrderDao.getByCode(shopOrder.getPurchaseOrderCode());
			model.put("userName",purchaseOrder.getName()!=null?purchaseOrder.getName():"");
			model.put("phone",purchaseOrder.getPhone()!=null?purchaseOrder.getPhone():"");
			model.put("addressDetail",purchaseOrder.getAddressDetail()!=null?purchaseOrder.getAddressDetail():"");
			model.put("city",purchaseOrder.getCity()!=null?purchaseOrder.getCity():"");
			model.put("express",shopOrder.getExpressType()!=null?shopOrder.getExpressType().toString():"");
			model.put("wayBillNum",shopOrder.getWayBillNum()!= null ? shopOrder.getWayBillNum() : "");
			model.put("payChannel",purchaseOrder.getPayChannel()!=null?purchaseOrder.getPayChannel().toString():"");
			model.put("transactionNo",purchaseOrder.getTransactionNo()!=null?purchaseOrder.getTransactionNo():"");
			model.put("memo",purchaseOrder.getMemo()!=null?purchaseOrder.getMemo():"");
			String shopName="叮当网";
			String shopPhone="";
			String shopMan="";
			String shopLocation="";
			DdmShop shop=ddmShopDao.getById(shopOrder.getShopId());
			if(shop!=null){
				shopName=shop.getName();
				shopPhone=shop.getContact();
				shopMan=shop.getLinkman();
				shopLocation=shop.getLocation();
			}
			model.put("shopPhone",shopPhone);
			model.put("shopMan",shopMan);
			model.put("shopLocation",shopLocation);
			model.put("shopName",shopName);
			model.put("saveMoney",shopOrder.getSaveMoney());
		}
		return  model;
	}

	/**ffl
	 * 2017-11-08 11:46:52
	 * 同意发货或拒绝发货
	 * @param shopOrder
	 * @param orderState
	 * @return
	 */
	public Boolean handleOrder(ShopOrder shopOrder, OrderState orderState, String handleDetail, User user) {
		if (shopOrder == null || orderState == null || StringUtils.isBlank(handleDetail) || user == null)
			return false;
		PurchaseOrder purchaseOrder=purchaseOrderDao.getByCode(shopOrder.getPurchaseOrderCode());
		synchronized (shopOrder) {
			if (!OrderState.Payment.equals(shopOrder.getOrderState()))
				return false;
			if (!OrderState.Delivery.equals(orderState) && !OrderState.Reject.equals(orderState))
				return false;

			//修改二级订单状态
			shopOrder.setHandlerId(user.getId());
			shopOrder.setHandleTime(new Date());
			shopOrder.setOrderState(orderState);
			shopOrder.setHandleDetail(handleDetail);
			shopOrderDao.modify(shopOrder);

			//修改三级订单状态
			GoodsOrder goodsOrderParam=new GoodsOrder();
			goodsOrderParam.setOrderState(OrderState.Payment);
			goodsOrderParam.setShopOrderCode(shopOrder.getCode());
			List<GoodsOrder> goodsOrderList = goodsOrderDao.queryList(-1, -1, goodsOrderParam);
			if (goodsOrderList != null && goodsOrderList.size() > 0) {
				for (GoodsOrder goodsOrder : goodsOrderList) {
					goodsOrder.setOrderState(orderState);
					goodsOrderDao.modify(goodsOrder);
					//如果不同意发货还要返还库存
					if (OrderState.Reject.equals(orderState)) {
						//修改商品销量
						DdmGoods goods=ddmGoodsDao.getById(goodsOrder.getGoodsId());
						synchronized (goods) {
							if(goods.getSalesVolume()-goodsOrder.getNum()>=0) {
								goods.setSalesVolume(goods.getSalesVolume() - goodsOrder.getNum());
								ddmGoodsDao.modify(goods);
							}
						}
						//添加库存日志
						InventoryLog inventoryLog=new InventoryLog();
						inventoryLog.setChangeNum(goodsOrder.getNum());
						inventoryLog.setCreateTime(new Date());
						inventoryLog.setInventorySource(InventorySource.OrderReject);
						inventoryLog.setType(FlowType.Add);
						inventoryLog.setUserId(goodsOrder.getUserId());
						inventoryLog.setCode(goodsOrder.getCode());
						inventoryLog.setRemark("驳回订单");
						//回放库存
						Inventory inventory=inventoryDao.getOnlyInventory(shopOrder.getShopId(),goodsOrder.getGoodsId(),goodsOrder.getGoodsSpecificationId());
						if(inventory!=null) {
							synchronized (inventory) {
								inventory.setInventory(inventory.getInventory() + goodsOrder.getNum());
								inventoryDao.modify(inventory);
							}
							inventoryLog.setInventoryId(inventory.getId());
							inventoryLogDao.add(inventoryLog);
						}
						if(goodsOrder.getSeckill()){
							coreLogic.updateInventory(goodsOrder.getSeckillGoodsId(),FlowType.Add);
						}
						//退卡券
						if(goodsOrder.getCardId()!=null){
							UserCards userCards=userCardsDao.getById(goodsOrder.getCardId());
							if(userCards!=null){
								returnUserCards(userCards);
							}
						}
						//取消增值服务
						serviceOrderDao.updateState(goodsOrder.getCode());
					}
				}
			}

			//不同意发货需要退还已支付的金额
			if (OrderState.Reject.equals(orderState)) {
				//退还用户支付金额 添加资金流水
				coreLogic.addFundsFlow(shopOrder.getUserId(),shopOrder.getPayMoney(), FlowSource.RejectOrder, FlowType.Add, shopOrder.getId(), shopOrder.getCode());
				coreLogic.changeMoneyAccount(shopOrder.getUserId(),shopOrder.getPayMoney(),FlowSource.RejectOrder,FlowType.Add);
			}

			return true;
		}

	}




	/**
	 * 发货
	 * ffl
	 * 2017-11-08 11:47:05
	 * @param shopOrder
	 * @param expressType
	 * @return
	 */
	public Boolean deliveryOrder(ShopOrder shopOrder, ExpressType expressType, String wayBillNum, User user){
		if (shopOrder == null || expressType == null || StringUtils.isBlank(wayBillNum) || user == null)
			return false;

		synchronized (shopOrder) {
			if (!OrderState.Delivery.equals(shopOrder.getOrderState()))
				return false;

			//修改二级订单状态
			shopOrder.setDeliverId(user.getId());
			shopOrder.setDeliverTime(new Date());
			shopOrder.setOrderState(OrderState.Deliveried);
			shopOrder.setExpressType(expressType);
			shopOrder.setWayBillNum(wayBillNum);
			shopOrder.setReceiptEndTime(DateUtils.addDays(new Date(), 7));//收货截止时间
			shopOrderDao.modify(shopOrder);
			//修改三级订单状态
			List<GoodsOrder> goodsOrderList = goodsOrderDao.getByShopOrderCode(shopOrder.getCode());
			if (goodsOrderList != null && goodsOrderList.size() > 0 ){
				for (GoodsOrder goodsOrder : goodsOrderList) {
					goodsOrder.setOrderState(OrderState.Deliveried);
					goodsOrder.setDeliverTime(new Date());
					goodsOrderDao.modify(goodsOrder);
				}
			}
			return true;
		}
	}


	/**
	 * 编辑订单  1同意发货 2驳回订单 3发货 4修改物流信息
	 * ffl
	 * 2017-11-12 11:15:56
	 * @param token
	 * @param handleDetail 处理详情
	 * @param shopOrderId  订单id
	 * @param handleValue   4同意发货  11不同意发货
	 * @param expressTypeValue  物流公司 1圆通速递 2申通快递 3百世汇通 4中通速递 5韵达快运 6邮政包裹 7天天快递 8顺丰速递 9EMS 10宅急送 11全峰快递 12邦德快递
	 * @param wayBillNum  物流单号
	 * @return
	 */
	public String editDoShopOrder(String token, String handleDetail, String shopOrderId, String handleValue, String expressTypeValue, String wayBillNum) {
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(shopOrderId)) {
			return CodeContent.getModelByCode(0,"请指定编辑的商品订单",null);

		}

		ShopOrder shopOrder = shopOrderDao.getById(NumberUtils.toInt(shopOrderId));
		if (shopOrder == null) {
			return CodeContent.getModelByCode(0,"编辑的订单不存在",null);

		}
        ModelMap model=new ModelMap();
		String goodsMsg="";
		if (OrderState.Payment.equals(shopOrder.getOrderState())) {//订单处于支付状态时
			if (StringUtils.isBlank(handleDetail))
				return CodeContent.getModelByCode(0,"请输入处理详情",null);


			if (handleDetail.length() > 300)
				return CodeContent.getModelByCode(0,"处理详情不能大于300",null);


			if (!NumberUtils.isDigits(handleValue))
				return CodeContent.getModelByCode(0,"请选择订单的处理类型",null);


			OrderState orderState = OrderState.getByIntValue(NumberUtils.toInt(handleValue));
			if (orderState == null)
				return CodeContent.getModelByCode(0,"请选择订单的处理类型",null);

			if (!OrderState.Delivery.equals(orderState) && !OrderState.Reject.equals(orderState))
				return CodeContent.getModelByCode(0,"请选择订单的处理类型",null);

			Boolean result=handleOrder(shopOrder,orderState,handleDetail,user);
			if (result){
				return CodeContent.getModelByCode(1,"",null);
			}else {
				return CodeContent.getModelByCode(0,"操作失败",null);
			}

		} else if (OrderState.Delivery.equals(shopOrder.getOrderState())) {    //订单处于待发货状态时
			if (StringUtils.isBlank(expressTypeValue) || !NumberUtils.isDigits(expressTypeValue))
				return CodeContent.getModelByCode(0,"请选择快递公司",null);

			ExpressType expressType = ExpressType.getByIntValue(NumberUtils.toInt(expressTypeValue));
			if (expressType == null)
				return CodeContent.getModelByCode(0,"快递公司不存在",null);


			if (StringUtils.isBlank(wayBillNum))
				return CodeContent.getModelByCode(0,"请填写运单号",null);


			Boolean deliveryResult = deliveryOrder(shopOrder,expressType,wayBillNum,user);

			if (deliveryResult){
				if(hasLmie(shopOrder)){
					goodsMsg="操作成功，请填写商品订单 商品唯一识别码";
				}
			}else {
				return CodeContent.getModelByCode(0,"操作失败",null);
			}
		} else if (OrderState.Deliveried.equals(shopOrder.getOrderState())) {    //订单处于已发货状态时
			if (StringUtils.isBlank(expressTypeValue) || !NumberUtils.isDigits(expressTypeValue))
				return CodeContent.getModelByCode(0,"请选择快递公司",null);

			ExpressType _expressType = ExpressType.getByIntValue(NumberUtils.toInt(expressTypeValue));
			if (_expressType == null)
				return CodeContent.getModelByCode(0,"快递公司不存在",null);

			if (StringUtils.isBlank(wayBillNum))
				return CodeContent.getModelByCode(0,"请填写运单号",null);

			shopOrder.setWayBillNum(wayBillNum);
			shopOrder.setExpressType(_expressType);
			shopOrderDao.modify(shopOrder);
			if(hasLmie(shopOrder)){
				goodsMsg="操作成功，请填写商品订单 商品唯一识别码";
			}
		}

        model.put("goodsMsg",goodsMsg);
		return CodeContent.getModelByCode(1,"",model);
	}


	public Boolean hasLmie(ShopOrder shopOrder){
		if(shopOrder==null)
			return false;
		List<GoodsOrder> goodsOrderList=goodsOrderDao.getByShopOrderCode(shopOrder.getCode());
		if(goodsOrderList!=null&&goodsOrderList.size()>0){
			for (int i=0;i<goodsOrderList.size();i++){
				if(goodsOrderList.get(i).getHasLmie()){
					if(goodsOrderList.get(i).getIdentifyCode()==null){
						return true;
					}

				}
			}
		}else {
			return false;
		}
		return  false;
	}

	/**
	 *  添加商品订单  商品唯一标识码
	 *  ffl
	 *  2017-11-13 11:54:41
	 * @param token
	 * @param goodsOrderId
	 * @param goodsLmie
	 * @return
	 */
	public String addGoodsLmie(String token,String goodsOrderId,String goodsLmie){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(goodsOrderId)) {
			return CodeContent.getModelByCode(0,"请指定编辑的商品订单",null);

		}

		GoodsOrder goodsOrder=goodsOrderDao.getById(NumberUtils.toInt(goodsOrderId));
		if (goodsOrder == null) {
			return CodeContent.getModelByCode(0,"编辑的订单不存在",null);

		}
		if(OrderState.Create.equals(goodsOrder.getOrderState())|| OrderState.Payment.equals(goodsOrder.getOrderState())){
			return  CodeContent.getModelByCode(0,"创建状态和支付状态 不能添加",null);
		}
		if(com.stlm2.util.StringUtils.isNullOrEmpty(goodsLmie)){
			return CodeContent.getModelByCode(0,"商品唯一标识码不能为空",null);
		}
		if(goodsOrder.getHasLmie()){
			goodsOrder.setIdentifyCode(goodsLmie);
			goodsOrderDao.modify(goodsOrder);
			List<ServiceOrder> serviceOrderList=serviceOrderDao.getByGoodsOrderCode(goodsOrder.getCode());
			if(serviceOrderList!=null&&serviceOrderList.size()>0){
				for (ServiceOrder serviceOrder:serviceOrderList) {
					serviceOrder.setImie(goodsLmie);
					serviceOrderDao.modify(serviceOrder);
				}
			}

		}
		return CodeContent.getModelByCode(1,"",null);
	}


	/**
	 * 获取商品订单list
	 * ffl
	 * 2017-11-13 15:02:42
	 * @param token
	 * @param shopOrderCode
	 * @param pageNum
	 * @return
	 */
	public String goodsOrderList(String token,String shopOrderCode,String pageNum){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (com.stlm2.util.StringUtils.isNullOrEmpty(shopOrderCode)) {
			return CodeContent.getModelByCode(0,"未传入仓库订单编号",null);

		}
		int pageNo=1;
		if(NumberUtils.isDigits(pageNum)){
			pageNo=NumberUtils.toInt(pageNum);
		}else {
			return CodeContent.getModelByCode(0,"未传查询页数",null);
		}
		GoodsOrder param=new GoodsOrder();
		param.setShopOrderCode(shopOrderCode);
		PageView pageView=goodsOrderDao.queryPageView(pageNo,10,param);
		ModelMap model = new ModelMap();
		if (pageView != null) {
			model.put("goodsOrderList", convertGoodsOrderDetail(pageView.getRecords()));
			model.put("recordsTotal",pageView.getRowCount());
			model.put("totalPage", pageView.getPageCount());
		}
		model.put("pageNo", pageNo);
		model.put("code",1);
		model.put("msg","success");
		return new org.json.JSONObject(model).toString();
	}


	/**
	 * 商品订单详情
	 * ffl
	 * 2017-11-13 15:06:11
	 * @param token
	 * @param id
	 * @return
	 */
	public String getByGoodsOrderId(String token,String id){
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}

		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入订单id",null);
		}
		GoodsOrder goodsOrder=goodsOrderDao.getById(NumberUtils.toInt(id));
		if(goodsOrder==null){
			return CodeContent.getModelByCode(0,"未找到订单",null);
		}
		return CodeContent.getModelByCode(1,"",buildModelGoodsOrderDetail(goodsOrder));
	}


	/**
	 * 到店自取   线下支付
	 * ffl
	 * 2018-01-12 15:51:58
	 * @param token
	 * @param password
	 * @param shopOrderId
	 * @return
	 */
	public String confirmShopOrder(String token, String password, String shopOrderId) {
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(password)) {
			return CodeContent.getModelByCode(0,"请输入正确的操作口令",null);

		}
		if (user.getCompanyCode()-NumberUtils.toInt(password)!=0){
			return CodeContent.getModelByCode(0,"请输入正确的操作口令",null);
		}
		if (!NumberUtils.isDigits(shopOrderId)) {
			return CodeContent.getModelByCode(0,"请指定编辑的商品订单",null);

		}

		ShopOrder shopOrder = shopOrderDao.getById(NumberUtils.toInt(shopOrderId));
		if (shopOrder == null) {
			return CodeContent.getModelByCode(0,"编辑的订单不存在",null);

		}
		PurchaseOrder purchaseOrder=purchaseOrderDao.getByCode(shopOrder.getPurchaseOrderCode());
		if (purchaseOrder==null){
			return CodeContent.getModelByCode(0,"编辑的购买订单不存在",null);
		}

		ModelMap model=new ModelMap();

		if (OrderState.Create.equals(shopOrder.getOrderState())&&DeliveryType.SelfPickup.equals(shopOrder.getDeliveryType())) {//订单处于创建状态时
			List<GoodsOrder> goodsOrderList=goodsOrderDao.getByShopOrderCode(shopOrder.getCode());
			if (goodsOrderList!=null&&goodsOrderList.size()>0){
				Date time=new Date();
				for (GoodsOrder goodsOrder :goodsOrderList) {
					goodsOrder.setOrderState(OrderState.Receipt);
					goodsOrder.setHasComment(true);
					goodsOrder.setDeliverTime(time);
					goodsOrder.setReceiptTime(time);
					goodsOrderDao.modify(goodsOrder);
				}

				shopOrder.setHasComment(true);
				shopOrder.setReceiptTime(time);
				shopOrder.setDeliverTime(time);
				shopOrder.setOrderState(OrderState.Receipt);
				shopOrderDao.modify(shopOrder);
				purchaseOrder.setOrderState(OrderState.Payment);
				purchaseOrderDao.modify(purchaseOrder);
				//用户积分
				if(shopOrder.getPayMoney().compareTo(new BigDecimal(0))==1){
					BigDecimal integral=shopOrder.getPayMoney().multiply(new BigDecimal(0.01));

					//添加积分
					Account account=accountDao.getByUserId(shopOrder.getUserId());
					account.setRemainJiFen(account.getRemainJiFen().add(integral));
					account.setTotalJiFen(account.getTotalJiFen().add(integral));
					accountDao.modify(account);

					//添加积分流水
					coreLogic.addFundsFlow(shopOrder.getUserId(),integral, FlowSource.GiveIntegral, FlowType.Add, shopOrder.getId(), shopOrder.getCode());
				}

			}else {
				return CodeContent.getModelByCode(0,"编辑的商品订单不存在",null);
			}

		}


		return CodeContent.getModelByCode(1,"",model);
	}

	/**
	 * 订单查询用  选择店铺或仓库
	 * ffl
	 * 2017-11-13 16:54:08
	 * @return
	 */
	public String getShopList(){
		List<DdmShop> shopList=ddmShopDao.queryAll();
		return CodeContent.getModelByCode(1,"",convertShopCrm(shopList));
	}

	public List<ModelMap> convertShopCrm(List<DdmShop> shopList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (shopList!= null && shopList.size() > 0) {
			for (DdmShop shop: shopList) {
				ModelMap map = buildModelShopCrm(shop);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelShopCrm(DdmShop shop) {
		ModelMap model = new ModelMap();
		if (shop!=null) {
			model.put("id", shop.getId());
			model.put("name",shop.getName());

		}
		return  model;
	}

	public void  cancelOrderThread(){

		for (DateSourceType dateSourceType: DateSourceType.values()) {
			Thread threadS=  new Thread_v1(dateSourceType);
			threadS.start();
		}

	}
	class  Thread_v1 extends  Thread{
		DateSourceType dateSourceType1;
		Thread_v1(DateSourceType dateSourceType){
			this.dateSourceType1 = dateSourceType;

		}
		public void run() {

			try {
				System.out.println("取消一天之前未支付的订单   公司编号:"+dateSourceType1.getIntValue()+"--执行开始");
				DBContextHolder.setDBType(dateSourceType1.toString());
				cancelOrder();
				DBContextHolder.clearDBType();
				System.out.println("取消一天之前未支付的订单   公司编号:"+dateSourceType1.getIntValue()+"--执行结束");
			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				System.out.println("叮当淘");
			}

		}
	}


	public void  confirmReceiptOrderThread(){

		for (DateSourceType dateSourceType: DateSourceType.values()) {
			Thread threadS=  new Thread_v2(dateSourceType);
			threadS.start();
		}

	}
	class  Thread_v2 extends  Thread{
		DateSourceType dateSourceType1;
		Thread_v2(DateSourceType dateSourceType){
			this.dateSourceType1 = dateSourceType;

		}
		public void run() {

			try {
				System.out.println("改发货7天后还未更改确认收货的订单为确认收货   公司编号:"+dateSourceType1.getIntValue()+"--执行开始");
				DBContextHolder.setDBType(dateSourceType1.toString());
				confirmReceiptOrder();
				DBContextHolder.clearDBType();
				System.out.println("改发货7天后还未更改确认收货的订单为确认收货   公司编号:"+dateSourceType1.getIntValue()+"--执行结束");
			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				System.out.println("叮当淘");
			}

		}
	}
}